<?php
ob_start();
session_start();

include 'top3.php';
include("utils.php");
main_content("mainBuySpace();");
if(!isset($_SESSION[siteuserId]) ||  $_SESSION[siteuserId]=='')
	echo '<script>window.location="index.php"</script>';
function mainBuySpace()
{
// 	echo '<pre>';
// 	print_r($_REQUEST);
// 	echo '</pre>';

	if($_SESSION['langId']!="")
	{
		$langId=$_SESSION['langId'];
	}
	else
	{
		$langId="1";
	}


	// For file upload coding
	if($_REQUEST['network_type']!='text')
	{
		if($_FILES["file"]["name"])
			if ($_FILES["file"]["error"] > 0)
			{
			echo "Error: " . $_FILES["file"]["error"] . "<br />";
			}
			else
			{
			$file_name = $_FILES["file"]["name"];
			$extension = explode('.',$file_name);  
			move_uploaded_file($_FILES["file"]["tmp_name"],"upload_network/" . $_SESSION[siteuserId]."_".time() .".".$extension[1]);
			$_SESSION['uploaded_file_name']=$_SESSION[siteuserId] ."_".time() .".".$extension[1];
			}
		@unlink('upload_network/'.$_REQUEST['uploaded_file_name']);
	}
	// End of file upload query


###################### code to find out the sites which are associated with network  matching the netork(country id) and site(country id) starts #######################

$adtype_retrieve=$_REQUEST['network_type'];
$network_id=$_REQUEST['network_id'];
$no_of_clicks_retrieve=$_REQUEST['radPurchase'];
$network_min_price_retrieve=$_REQUEST['network_min_price'];
$total_cost_retrieve=$no_of_clicks_retrieve * $network_min_price_retrieve;

$SELECT_network_country="select * from network_country where networkId = '".$network_id."'";
$EXE_network_country=mysql_query($SELECT_network_country);
$site_id='';
while($ROW_network_country=mysql_fetch_array($EXE_network_country))
{
//echo "<script>alert('".$ROW_network_country['countryId']."')</script>";
// 		$select_sitemaser_country="select * from adsite_master where $ROW_network_country['countryId'] in adsite_master.adcountryId";
		$select_adsite_master_country="select * from adsite_master";
		$exe_adsite_master=mysql_query($select_adsite_master_country);
		while($row_adsite_master=mysql_fetch_array($exe_adsite_master))
		{
			if($row_adsite_master['adcountryId']!='')
			{
//echo "<script>alert('".$row_adsite_master['adcountryId']."')</script>";
			$arr=explode(',',$row_adsite_master['adcountryId']);
			//print_r($arr);
			if(in_array($ROW_network_country['countryId'], $arr))
			{
				if($site_id=='')
				{
					$site_id=$row_adsite_master['adsiteId'];
					//echo "<script>alert('hi')</script>";
				}
				else
				{
					if($site_id==$row_adsite_master['adsiteId'])
					{
						//$site_id.=",".$row_adsite_master['adsiteId'];
					}
					else
					{
						$site_id.=",".$row_adsite_master['adsiteId'];
					}
				}
			}
			else
			{
			}
			}
		}
}
//echo "<script>alert('".$site_id."')</script>";
$arr_site_id=explode(',',$site_id);

$unique_arr_site_id=array_unique($arr_site_id);
//print_r($unique_arr_site_id);
//$count_arr=count($unique_arr_site_id);
$end_index=end($unique_arr_site_id);
$item_country='';
for($k=0;$k<$end_index;$k++)
{
	if($unique_arr_site_id[$k]!='')
	{
		if($item_country == '')
		{
			$item_country=$unique_arr_site_id[$k];
		}
		else
		{
			$item_country.=",".$unique_arr_site_id[$k];
		}
	}
	
}
//echo "<script>alert('".$item_country."')</script>";

###################### code to find out the sites which are associated with network  matching the netork(country id) and site(country id) ends #######################



###################### code to find out the sites which are associated with network  matching the netork(category id) and site(category id) starts #######################



$SELECT_network_category="select * from network_ad_category where networkId = '".$network_id."'";
$EXE_network_category=mysql_query($SELECT_network_category);
$site_id_category='';
while($ROW_network_category=mysql_fetch_array($EXE_network_category))
{
//echo "<script>alert('".$ROW_network_category['categoryId']."')</script>";
// 		$select_sitemaser_country="select * from adsite_master where $ROW_network_country['countryId'] in adsite_master.adcountryId";
		$select_adsite_master_category="select * from adsite_master where adcategoryId = '".$ROW_network_category['categoryId']."'";
		$exe_adsite_master_category=mysql_query($select_adsite_master_category);
		if(mysql_num_rows($exe_adsite_master_category)>0)
		{
			while($row_adsite_master_category=mysql_fetch_array($exe_adsite_master_category))
			{
				if($site_id_category=='')
				{
					$site_id_category.=$row_adsite_master_category['adsiteId'];
				}
				else
				{
					$site_id_category.=",".$row_adsite_master_category['adsiteId'];
				}
			}
		}
}
//echo "<script>alert('".$site_id_category."')</script>";
$arr_site_id_category=explode(',',$site_id_category);

$unique_arr_site_id_category=array_unique($arr_site_id_category);
//print_r($unique_arr_site_id_category);
//$count_arr=count($unique_arr_site_id);
$end_index_category=end($unique_arr_site_id_category);
$item_category='';
for($m=0;$m<$end_index_category;$m++)
{
	if($unique_arr_site_id_category[$m]!='')
	{
		if($item_category == '')
		{
			$item_category=$unique_arr_site_id_category[$m];
		}
		else
		{
			$item_category.=",".$unique_arr_site_id_category[$m];
		}
	}
	
}
//echo "<script>alert('".$item_category."')</script>";

###################### code to find out the sites which are associated with network  matching the netork(category id) and site(category id) ends #######################
if($item_country=='')
{
	$item=$item_category;
}
else
{
	$item=$item_country.",".$item_category;
//echo "<script>alert('".$item."')</script>";
	$item_site_country_category_explode=explode(",",$item);
$unique_arr_site_id_country_category=array_unique($item_site_country_category_explode);
// 	for($item_count=0;$item_count<count($item_site_country_category_explode);$item_count++)
// 	{
// 		if($item_site_country_category=='')
// 		{
// 			$item_site_country_category=$item_site_country_category_explode[$item_count];
// 		}
// 		else
// 		{
// 			$item_site_country_category.=",".$item_site_country_category_explode[$item_count];
// 		}
// 	}

// echo "<script>alert('".$item_site_country_category."')</script>";
	//$item=array_merge((array)$item_country, (array)$item_category);

// 	$unique_arr_site_id_country_category=array_unique($item_site_country_category);
// echo "<script>alert('".$unique_arr_site_id_country_category."')</script>";
// echo "<pre>";
// print_r($unique_arr_site_id_country_category);
// echo "</pre>";
	$end_index_country_category=end($unique_arr_site_id_country_category);

	$item_country_category='';
for($n=0;$n<$end_index_country_category;$n++)
{
	if($unique_arr_site_id_country_category[$n]!='')
	{
		if($item_country_category == '')
		{
			$item_country_category=$unique_arr_site_id_country_category[$n];
		}
		else
		{
			$item_country_category.=",".$unique_arr_site_id_country_category[$n];
		}
	}
	
}
$item=$item_country_category;
}





if(isset($_REQUEST[addtocart]))
{
//$start_date=now();
		if($adtype_retrieve=='text')
		{
			$sqlAdMaster = "insert into advertise_master set langId='".$langId."',adTitle='".$_REQUEST[txtHeadline]."',adTitle_personal='".$_REQUEST[txtAdName]."',adType='WEB',destinationUrl='".$_REQUEST[txtUrl]."',startDate=now(),adPrice='".$total_cost_retrieve."',siteuserId='".$_SESSION[siteuserId]."',ad_Type='network'";
		}
		else
		{
			$sqlAdMaster = "insert into advertise_master set langId='".$langId."',adTitle='".$_REQUEST[txtHeadline]."',adTitle_personal='".$_REQUEST[txtAdName]."',adType='WEB',destinationUrl='".$_REQUEST[txtUrl]."',startDate=now(),adPrice='".$total_cost_retrieve."',siteuserId='".$_SESSION[siteuserId]."',ad_Type='network',ad_image='".$_SESSION['uploaded_file_name']."'";
		}
 	mysql_query($sqlAdMaster)or die(mysql_error());;
 	$insertid = mysql_insert_id();


		if (empty($no_of_clicks_retrieve)){
			$no_of_clicks_retrieve=0;
		}
 	 $sqlAdDetails = "insert into advertise_details set advertiseId='".$insertid."',adsiteId='".$item."',adDisplayType ='".$adtype_retrieve."',networkId = '".$network_id."',clicks_to_purchase = '".$no_of_clicks_retrieve."' ";
 	mysql_query($sqlAdDetails)or die(mysql_error());

 

 	 $sql_TempOrder = "insert into tblordertemp set advertiseId='".$insertid."',session_id='".session_id()."',siteuserId='".$_SESSION['siteuserId']."',adsiteId  ='".$item."',adspace_price ='".$total_cost_retrieve."',total_amount='".$total_cost_retrieve."',order_date=now(),Quentity='1'";

 	mysql_query($sql_TempOrder)or die(mysql_error());

	echo '<script>window.location="cart.php?tab=buy_ads&subMenu=2"</script>';

	
}
?>




<!-- ######################################################      script starts here         ##################################### -->





<script>

function submit_browse_form()
{
document.getElementById('frmAvertise').submit();
return true;
}

function main_page()
{
window.location="buyNetworkAds.php" ;
}

function showhidSelectBox(mode)
{
if(mode!='none')
{

	document.getElementById('txtUrl').value=document.getElementById('selExistingAd').value;

}
else
{

	document.getElementById('txtUrl').value='';
document.getElementById('txtUrl').readOnly=false;
}
	document.getElementById('tdExistingAd').style.display=mode;
}



function validation(type_id)
{
 
var txtHeadline = document.getElementById("txtHeadline").value;
var txtUrl = document.getElementById("txtUrl").value;

if(type_id=='text'){
var text_description = document.getElementById("text_description").value; 

if(text_description != "")    {
        document.getElementById("validate_text_description").style.display="none";
    }
}

if(txtHeadline != "")    {
        document.getElementById("txtHeadline_validate").style.display="none";
    }

if(txtUrl != "" || txtUrl != "http://")    {
        document.getElementById("txtUrl_validate").style.display="none";
    }


if(txtHeadline == "")    {
        document.getElementById("txtHeadline_validate").style.display="block";
        //document.getElementById("txtHeadline_validate").innerHTML="Please Enter Headline!";
        document.getElementById("txtHeadline").focus();
        return false;
    }

if(type_id=='text'){
if(text_description == "")    {
        document.getElementById("validate_text_description").style.display="block";
        document.getElementById("validate_text_description").innerHTML="Please Enter Desc!";
        document.getElementById("text_description").focus();
        return false;
    }
}


if(txtUrl == "" || txtUrl == "http://")    {
        document.getElementById("txtUrl_validate").style.display="block";
        //document.getElementById("txtUrl_validate").innerHTML="Please Enter Destination Url!";
        document.getElementById("txtUrl").focus();

    
        return false;
    }

if(txtUrl != "")    {
	
	var v = new RegExp();
	v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
	if (!v.test(document.getElementById("txtUrl").value)) {
		alert("You must supply a valid URL.");
        document.getElementById("txtUrl").focus();
	return false;					      }
        
    		    }		


return true;
}

function preview_heading()
{
document.getElementById("prev_heading").value = document.getElementById("txtHeadline").value;
document.getElementById("prev_heading").innerHTML= document.getElementById("txtHeadline").value;
document.getElementById("prev_heading").style.display = 'block';
}

function preview_text_description_func()
{
document.getElementById("preview_text_description").value = document.getElementById("text_description").value;
document.getElementById("preview_text_description").innerHTML= document.getElementById("text_description").value;
document.getElementById("preview_text_description").style.display = 'block';
}

function una_dis(landing_val)
{
	var arr=landing_val.split("-");
	document.getElementById('show_url').style.display='';
	document.getElementById('show_url').innerHTML='<a href='+arr[1]+'>'+arr[1]+'</a>';
}

function retrieve_data(id)
{
var id = id;
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
var res = xmlHttp.responseText;
//delete_garbage_network();
//alert(xmlHttp.responseText);

var allVal=new Array();

allVal = res.split(",");
//alert("Count--->"+allVal.length);ram
document.getElementById('txtHeadline').value = allVal[0];
document.getElementById('txtAdName').value = allVal[1];
document.getElementById('txtUrl').value = allVal[2];

      }
    }

  xmlHttp.open("GET","retrieve_ad_data.php?id="+id,true);
  xmlHttp.send(null);
  return false; 
}


function hidelanding()
{

document.getElementById('landing_url').style.display = 'none';
document.getElementById('landing_url_dd').style.display = 'none';
document.getElementById('nlp').style.display = 'none';
document.getElementById('nlp1').style.display = 'none';

}

function showlanding()
{
document.getElementById('landing_url').style.display = 'block';
document.getElementById('landing_url_dd').style.display = 'block';
document.getElementById('nlp').style.display = 'block';
document.getElementById('nlp1').style.display = 'block';
}
</script>






<!-- ###########################################       script ends here          ################################# -->





<table width="90%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td valign="top" align="center"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
                  <tr>
                    <td width="20%" valign="top"><?php include("left_pannel.php"); ?></td>
	<td width="10">&nbsp;</td>
                    <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                              <td width="11"><img src="images/PinkBorderTopLeft.jpg" alt="" width="11" height="11"></td>
                              <td class="PinkBoxTopBg"><img src="images/spacer.gif" alt="" width="10" height="11"></td>
                              <td width="11"><img src="images/PinkBorderTopRight.jpg" alt="" width="11" height="11"></td>
                            </tr>
                        </table></td>
                      </tr>
                      <tr>
                        <td class="PinkTwosideBorder" valign="top"><table cellspacing="4" cellpadding="4" border="0">
              <TR>
                <TD align="left" colspan="9"><font class="sky font-14"><strong>1.Create Your Ad</strong></font>&nbsp;2.&nbsp;Shopping Cart&nbsp;3.&nbsp;Payment&nbsp;4.&nbsp;Your Order&nbsp;5.&nbsp;Order Confirmation </TD>
              </TR>
              <TR>
                <TD align="left">&nbsp;</TD>
              </TR>
              <TR>
                <TD align="left"><table style="border:#CCCCCC 1px solid;" cellspacing="0" cellpadding="0">
                    <tr>
                      <td><!--LEFT TD-->
                        <table cellspacing="0" cellpadding="0" border="0">
                          <form name="frmAvertise" method="POST" action="" enctype="multipart/form-data" id="frmAvertise">
                          
                          <!--<input type="hidden" name="duration" value="<?php// echo $_REQUEST[days];?>">
                          <input type="hidden" name="enddate" value="<?php// echo $_REQUEST[duration];?>">-->
                          <!--<input type="hidden" name="adspaceid" value="<?php// echo $_REQUEST[id];?>">-->

			<input type="hidden" name="network_type" value="<?php echo $adtype_retrieve;?>">
			<input type="hidden" name="network_id" value="<?php echo $network_id;?>">
			<input type="hidden" name="adsite_id" id="adsite_id" value="<?php echo $item; ?>">
			<input type="hidden" name="uploaded_file_name" value="<?php echo $_SESSION['uploaded_file_name']; ?>">
			<input type="hidden" name="radPurchase" id="radPurchase" value="<?php echo $no_of_clicks_retrieve; ?>">
			<input type="hidden" name="network_min_price" id="network_min_price" value="<?php echo $network_min_price_retrieve; ?>">
			<input type="hidden" name="total_cost" id="total_cost" value="<?php echo $total_cost_retrieve; ?>">
                          <tr>

                          <td valign="top" align="left"><table cellpadding="5" cellspacing="2" border="0">
                              <tr>
                                <td width="300" class="sitename" style="border-right:#cccccc 1px solid;" colspan="2">Create Your Ad</td>
                              </tr>

<?php
			$query_adtype="select * from advertise_details where adDisplayType = '".$adtype_retrieve."'  ";
			
			$res_adtype=mysql_query($query_adtype);

 			?>
                              <TR>
                                <TD align="right"><input checked="true" onclick="showhidSelectBox('none')" type="radio" name="radSelectAd" id="radSelectAd1" checked="true" ></TD>
                                <td align="left"><strong>Create Your Ad</strong></td>
                              </tr>

                              <TR>
                                <TD align="right"><input onclick="showhidSelectBox('')"  type="radio" name="radSelectAd" id="radSelectAd2"></TD>
                                <td align="left"><strong>Use An Existing Ad</strong></td>
                              </tr>

                              <tr>
                                <TD colspan="2" id="tdExistingAd" style="display:none;">&nbsp;
                                  <select name="selExistingAd" id="selExistingAd" onchange="return retrieve_data(this.value);">
                                    <?php
						  while($row_adtype= mysql_fetch_array($res_adtype)){
						  $q = "select * from advertise_master where advertiseId = ".$row_adtype['advertiseId']." and siteuserId=".$_SESSION['siteuserId']." ";
						  $res = mysql_query($q);
						  $row = mysql_fetch_array($res);
                                    ?>
                                    <option value="<?php echo $row['advertiseId']; ?>"> <?php echo $row['adTitle'];?></option>
                                    <?php
                                        }
                                        ?>
                                  </select>
                                  <!--left td-->
                                </TD>
                              </tr>




                              <?php
			
   if($adtype_retrieve == 'text' || $adtype_retrieve == 'thumbnail'){ ?>
                              <tr>
                                <TD colspan="2">&nbsp;*Headline:</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="text" name="txtHeadline" id="txtHeadline" value="<?php if($_REQUEST['txtHeadline']!=''){ echo $_REQUEST['txtHeadline']; } ?>" onkeyup="return preview_heading();"></TD>
                                <TD colspan="2" id="txtHeadline_validate" style="display:none;">Please Enter Url!</TD>
                              </tr>
                              <?php } ?>
                              <?php if($adtype_retrieve == 'text'){ ?>
                              <tr>
                                <TD colspan="2">&nbsp;*Add Description</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <textareA name="text_description" id="text_description" onkeyup="return preview_text_description_func();"></textareA></TD>
                                <TD colspan="2" id="validate_text_description" style="display:none;">Please Enter Description !</TD>
                              </tr>
                              <?php } ?>
                              <?php if($adtype_retrieve == 'banner' || $adtype_retrieve == 'thumbnail'){ ?>
                              <tr>
                                <TD colspan="2">&nbsp;*Upload File:  (Max. 90 KB) (728 x 90 preferred)</TD>
                              </tr>
                              <tr>
                                <TD colspan="2"><input type="file" name="file" id="file" onchange="return submit_browse_form();" />
                                  <inpUT type="hidden" name="sahara" value="11">
                                </TD>
                              </tr>
                           
                              
                              <?php } ?> 





                              <tr>
                                <TD colspan="2">&nbsp;*Destination URL (http://):</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="text" name="txtUrl" id="txtUrl" value="http://"></TD>
                                <TD colspan="2" id="txtUrl_validate" style="display:none;">Please Enter Destiny url!</TD>
                              </tr>




                              <tr>
                                <TD colspan="2">&nbsp;Ad Name (For personal reference)</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="text" name="txtAdName" id="txtAdName" value="<?php if($_REQUEST['txtAdName']!=''){ echo $_REQUEST['txtAdName']; } ?>"></TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="button" value="Cancel" onclick="return main_page();">
                                  &nbsp;
                                  <input type="submit" value="Proceed To Cart" name="addtocart" onclick="return validation('<?php echo $adtype_retrieve;?>');"></TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;</TD>
                              </tr>
                            </table></td>
                          <td width="50px" valign="top">&nbsp;</td>
                            <!--Middle TD-->
                            <td valign="top"><!--Right TD START-->
                              <table>
                                <tr valign="top">
                                  <td class="sitename" style="border-right:#cccccc 1px solid;" valign="top" align="center">Preview</td>
                                </tr>
                                <tr>
                                  <td align="center" id="prev_heading">Headline Goes Here</td>
                                </tr>
                                <?php if($adtype_retrieve == 'thumbnail'){ ?>
                                <tr>
                                
									<?php 
									if(empty($_SESSION['uploaded_file_name']))
										
										echo '<td><imG src="images/noimage.jpg" height="100px"></td>';
									else
										echo "<td><imG src='upload_network/".$_SESSION['uploaded_file_name']."' height=\"100px\"></td>";
									
									
									?>
								
                                </tr>
                                <?php } ?>
                                <?php if($adtype_retrieve == 'text'){ ?>
                                <tr>
                                  <td align="center" id="preview_text_description">Ad Description Goes Here</td>
                                </tr>
                                <?php } ?>
                                <?php if($adtype_retrieve == 'banner'){ ?>
                                <tr>
									<?php 
									if(empty($_SESSION['uploaded_file_name']))
										
										echo '<td><imG src="images/noimage.jpg" height="100px"></td>';
									else
										echo "<td><imG src='upload_network/".$_SESSION['uploaded_file_name']."' height=\"100px\"></td>";
									
									
									?>
                                </tr>
                                <?php } ?>
                                <tr>
                                  <td>Please note: The Preview will not display correctly if you do not set the "Text size" to "Normal" on your browser.</td>
                                </tr>
                              </table></td>
                            <!--Right TD END-->
                          </tr></form>
                        </table></td>
                    </tr>
                    
                    
                  </table></TD>
            </table></td>
                      </tr>
                      <tr>
                        <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                              <td width="11"><img src="images/PinkBorderBottomLeft.jpg" alt="" width="11" height="11"></td>
                              <td class="PinkBoxBottomBg"><img src="images/spacer.gif" alt="" width="10" height="11"></td>
                              <td width="11"><img src="images/PinkBorderBottomRight.jpg" alt="" width="11" height="11"></td>
                            </tr>
                        </table></td>
                      </tr>
                    </table></td>
                    
                    </tr>
                </table></td>
              </tr>
            </table>
<?php
}
?>
